package cn.edu.hzvtc.controller;

import cn.edu.hzvtc.pojo.*;
import cn.edu.hzvtc.service.msgService;
import cn.edu.hzvtc.service.unitService;
import cn.edu.hzvtc.service.userService;

import cn.edu.hzvtc.pojo.ReturnMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping("/msg")
public class MsgController {

    @Autowired
    private msgService msgService;
    @Autowired
    private unitService unitService;

    //获取用户登录信息
    @RequestMapping("/loginUser")
    @ResponseBody
    public ReturnMsg loginUser(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        System.out.println("loginUser=" + loginUser);
        return ReturnMsg.success().add("loginUser", loginUser);
    }

    //获取所有发送消息
    @RequestMapping("/msgs")
    @ResponseBody
    public ReturnMsg getUsers(@RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {
        //引入PageHelper分页插件
        //在查询之前只需要传入页码以及每页的大小
        PageHelper.startPage(pn, 5);
        User loginUser = (User) session.getAttribute("loginUser");
        //startPage方法紧跟第一个select查询就是一个分页查询
        List<Msg> msg = msgService.getSendMsgByUserId(loginUser.getId());
        //使用PageInfo包装查询结果，封装了分页信息和查询出的数据，只需将pageInfo交给页面即可
        PageInfo pageInfo = new PageInfo(msg, 5);

        return ReturnMsg.success().add("pageInfo", pageInfo);
    }

    //删除院校管理员信息
    @RequestMapping(value = "/msg/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg deleteMsg(@PathVariable("id") Integer id) {
        if (msgService.deleteMsg(id)) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    @RequestMapping(value = "/userUnits", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getUserUnits(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");

        List<Unit> units = unitService.getUnitByUserId(loginUser.getId());

        return ReturnMsg.success().add("units", units);
    }

    @RequestMapping(value = "/msg", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg save(@Valid Msg msg, Integer[] receiveUserId, BindingResult result, HttpSession session) {
        ;
        Set<Integer> set = new HashSet<Integer>();
        for (Integer i : receiveUserId) {
            set.add(i);
        }
        User loginUser = (User) session.getAttribute("loginUser");
        msg.setMsgSendUserId(loginUser.getId());
        msg.setMsgSendTime(new Date());
        msg.setMsgDelState(0);
        if (msgService.addMsg(msg, set) != 0) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    @RequestMapping(value = "/noAnswerCount", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getNoAnswerCount(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");


        int noAnswerCount = msgService.getCountByUserId(loginUser.getId(), 0);

        return ReturnMsg.success().add("noAnswerCount", noAnswerCount);
    }


    @RequestMapping(value = "/msgAnswers", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getMsgAnswers(@RequestParam(value = "pn", defaultValue = "1") Integer pn, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        //引入PageHelper分页插件
        //在查询之前只需要传入页码以及每页的大小
        PageHelper.startPage(1, pn * 4);
        //startPage方法紧跟第一个select查询就是一个分页查询
        List<MsgAnswer> msgAnswers = msgService.getReceiveMsgByUserId(loginUser.getId());
        //使用PageInfo包装查询结果，封装了分页信息和查询出的数据，只需将pageInfo交给页面即可
        PageInfo pageInfo = new PageInfo(msgAnswers);
        return ReturnMsg.success().add("pageInfo", pageInfo);
    }

    @RequestMapping(value = "/msgAnswer/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg modifyMsgAnswer(@PathVariable("id") Integer msgAnswerId, @Valid MsgAnswer msgAnswer) {
        msgAnswer.setId(msgAnswerId);
        msgService.updateMsgAnswer(msgAnswer);
        return ReturnMsg.success();
    }


    @RequestMapping(value = "/msg/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getMsg(@PathVariable("id") Integer id) {
        Msg msg = msgService.getMsgById(id);
        List<MsgCount> msgCountsResult = msgService.getReceiveMsgCountsById(id);
        List msgCounts = new ArrayList();
        List msgTexts = new ArrayList();

        if (msg.getMsgType() == 1) {
            msgTexts.add("未查收");
            msgTexts.add("已查收");
        } else if (msg.getMsgType() == 2) {
            msgTexts.add("未回复");
            msgTexts.add("已回复");
        } else {
            msgTexts.add("未投票");
            msgTexts.add("反对");
            msgTexts.add("赞成");
        }

        if (msgCountsResult.size() > 0) {
            MsgCount msgCount = msgCountsResult.get(0);
            if (msgCount == null || msgCount.getMsgState().intValue() != 0) {
                msgCounts.add(0L);
                msgCountsResult.add(0, null);
            } else
                msgCounts.add(msgCount.getCount());

            if (msgCountsResult.size() > 1) {
                msgCount = msgCountsResult.get(1);
            } else {
                msgCount = null;
            }

            if (msgCount == null || (msg.getMsgType() == 3 && msgCount.getMsgVote() != 0)) {
                msgCounts.add(0L);
                msgCountsResult.add(0, null);
            } else {
                msgCounts.add(msgCount.getCount());
            }

            if (msg.getMsgType() == 3) {
                if (msgCountsResult.size() > 2) {
                    msgCount = msgCountsResult.get(2);
                } else {
                    msgCount = null;
                }
                if (msgCount == null) {
                    msgCounts.add(0L);
                } else
                    msgCounts.add(msgCount.getCount());
            }
        }
        return ReturnMsg.success().add("msg", msg).add("msgCounts", msgCounts).add("msgTexts", msgTexts);
    }

    @RequestMapping(value = "/msgCount", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getCount(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");

        List<MsgCount> allCountsResult = msgService.getAllCountsByUserId(loginUser.getId());
        List<MsgCount> doneCountsResult = msgService.getDoneCountsByUserId(loginUser.getId());

        int noAnswerCount = msgService.getCountByUserId(loginUser.getId(), 0);
        int doneAnswerCount = msgService.getCountByUserId(loginUser.getId(), 1);
        List<Long> allCounts = new ArrayList<>();
        List<Long> doneCounts = new ArrayList<>();
        List<String> labels = new ArrayList<>();

        for (int i = 0; i < allCountsResult.size(); i++) {
            MsgCount msgCount = allCountsResult.get(i);
            MsgCount doneCount = null;
            allCounts.add(msgCount.getCount());

            if (i < doneCountsResult.size()) {
                doneCount = doneCountsResult.get(i);
            }


            if (doneCount == null) {
                doneCounts.add(0L);
                doneCountsResult.add(i, null);
            } else {
                doneCounts.add(doneCount.getCount());
            }

            if (msgCount.getMsgType() == 1) {
                labels.add("通知");
            } else if (msgCount.getMsgType() == 2) {
                labels.add("消息");
            } else {
                labels.add("投票");
            }
        }

        return ReturnMsg.success().add("allCounts", allCounts)
                .add("doneCounts", doneCounts)
                .add("labels", labels)
                .add("noAnswerCount", noAnswerCount)
                .add("doneAnswerCount", doneAnswerCount);
    }
}
